package cn.tedu.knows.portal.controller;

import cn.tedu.knows.portal.exception.ServiceException;
import cn.tedu.knows.portal.service.IUserService;
import cn.tedu.knows.portal.vo.RegisterVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@RestController
@Slf4j
public class SystemController {

    @Autowired
    private IUserService userService;

    @PostMapping("/register")
    public String register(RegisterVO registerVO) {
        log.debug("接收到表单信息:{}", registerVO);
        try {
            userService.registerStudent(registerVO);
            return "ok";
        } catch (ServiceException e) {
            log.error("业务异常", e);
            return e.getMessage();
        }
    }


    @Value("${knows.path}")
    private File knowsPath;
    @Value("${knows.host}")
    private String knowsHost;

    @PostMapping("/upload/file")
    public String upload(MultipartFile imageFile) throws IOException {
        System.out.println("开始运行控制器");
        // path:2022/03/14
        String path = DateTimeFormatter.ofPattern("yyyy/MM/dd")
                .format(LocalDateTime.now());
        File folder = new File(knowsPath, path);
        folder.mkdirs();
        String fileName = imageFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf("."));
        String name = UUID.randomUUID().toString() + ext;
        // E:/upload/2022/03/14/[uuid].jpg
        File file = new File(folder, name);
        imageFile.transferTo(file);
        // 回显url
        String url = knowsHost +     "/" +path+ "/" + name;
        // url : http://localhost:8899/2022/03/14/[uuid].jpg
        return url;


    }


}
